import Vue from 'vue'
import Vuex from 'vuex'
import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    token: getToken(),
    user:{},
  },
  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username
      const ps = userInfo.ps
      return new Promise((resolve, reject) => {
        login(username,ps).then(response => {
          const data = response
          console.log(data)
          setToken(data.newUser.token)
          commit('SET_TOKEN', data.newUser.token)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          const data = response
          commit('SET_USER', data.user)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_USER', {})
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER: (state, user) => {
      state.user = user
    }
  },
  getters:{
  token: state => state.token,
  user: state => state.user,
}
})

export default store